package com.swotxu.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.swotxu.common.to.es.SkuESModel;
import com.swotxu.mall.search.config.MallElasticSearchConfig;
import com.swotxu.mall.search.constant.ESConstant;
import com.swotxu.mall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Date: 2021/1/16 21:37
 * @Author: swotXu
 */
@Slf4j
@Service("productService")
public class ProductServiceImpl implements ProductService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuESModel> skuESModelList) throws IOException {
        // 保存到es
        // 1、建立索引 product
        // 2、给 es 保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuESModel skuESModel : skuESModelList) {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            indexRequest.id(skuESModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuESModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, MallElasticSearchConfig.COMMON_OPTIONS);
        boolean hasFailures = bulkResponse.hasFailures();
        if (hasFailures) {
            // TODO ES 商品上架错误后处理
            List<String> failureIds = Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.warn("商品上架错误！ids: {}", failureIds);
        }
        return !hasFailures;
    }
}
